<template>

  <div>

    <data-table
      ref="pagingTable"
      :options="options"
      :list-query="listQuery"
      @add="handleAdd"
      @multi-actions="handleMultiAction"
    >
      <template #filter-content>
        <repo-select v-model="repoId" />
        <dic-list-select v-model="listQuery.params.quType" dic-code="qu_type" title="请选择题型" />
        <chapter-select v-model="listQuery.params.chapterId" :repo-id="repoId" />
        <el-input v-model="listQuery.params.content" placeholder="试题内容" style="width: 200px;" class="filter-item" size="small" />
        <el-button-group class="filter-item" style="float:  right">
          <el-button v-permission="['qu:import']" size="small" icon="el-icon-upload2" @click="showImport">导入</el-button>
          <el-button v-permission="['qu:export']" size="small" icon="el-icon-download" @click="exportExcel">导出</el-button>
        </el-button-group>

      </template>

      <template #data-columns>

        <el-table-column
          label="试题内容"
          show-overflow-tooltip
        >

          <template v-slot="scope">
            <detail-link :id="scope.row.id" :title="getQuestionContent(scope.row)" to="UpdateQu" permission="qu:update" />
          </template>

        </el-table-column>

        <el-table-column
          v-if="repoId == null || repoId===''"
          label="题库"
          align="center"
          prop="repoId_dictText"
        />

        <el-table-column
          label="题型"
          align="center"
          width="120px"
        >
          <template v-slot="scope">
            <span>{{ getQuestionType(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="难度"
          align="center"
          width="120px"
          prop="level_dictText"
        />

        <el-table-column
          label="章节"
          align="center"
          width="200px"
          prop="chapterId_dictText"
        />

        <el-table-column
          label="创建时间"
          align="center"
          width="200px"
          prop="createTime"
        />

      </template>

    </data-table>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="chapterDialog"
      title="批量加入章节"
      width="30%"
    >

      <el-form label-position="left" label-width="100px">

        <el-form-item label="操作章节">
          <chapter-select v-model="chapterForm.chapterId" :repo-id="repoId" />
        </el-form-item>

        <el-row>
          <el-button type="primary" @click="handlerJoinChapters">保存</el-button>
        </el-row>

      </el-form>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="levelDialog"
      title="设置难易程度"
      width="30%"
    >

      <el-form label-position="left" label-width="100px">

        <el-form-item label="难易程度">
          <dic-list-select v-model="levelForm.level" dic-code="qu_level" title="请选择难易程度" />
        </el-form-item>

        <el-row>
          <el-button type="primary" @click="handlerBatchLevel">保存</el-button>
        </el-row>

      </el-form>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="repoDialog"
      title="批量迁移题库"
      width="30%"
    >

      <el-form label-position="left" label-width="100px">

        <el-form-item label="选择题库">
          <repo-select v-model="repoForm.toId" />
        </el-form-item>

        <el-row>
          <el-button type="primary" @click="handlerBatchRepo">保存</el-button>
        </el-row>

      </el-form>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="importDialog"
      title="导入试题"
      width="30%"
    >

      <el-descriptions :column="1" border>

        <el-descriptions-item>
          <template slot="label">
            所属题库
          </template>
          <repo-select v-model="repoId" />
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            导入文件
          </template>

          <import-excel
            v-if="listQuery.params.repoId!=null && listQuery.params.repoId !== ''"
            :data="{ repoId: listQuery.params.repoId}"
            title="试题"
            action="/api/qu/qu/import"
            template="/api/qu/qu/import/template"
            @success="importSuccess"
          />
          <span v-else>
            请先选择题库！
          </span>

        </el-descriptions-item>

      </el-descriptions>

      <el-row />

    </el-dialog>

  </div>

</template>

<script>
import DataTable from '@/components/DataTable'
import { exportExcel, joinChapters, clearChapters, batchLevel, batchRepo } from '@/api/qu/qu'
import ChapterSelect from '@/components/ChapterSelect'
import DicListSelect from '@/components/DicListSelect'
import RepoSelect from '@/components/RepoSelect'
import { getToken } from '@/utils/auth'
import ImportExcel from '@/components/ImportExcel'
import permission from '@/directive/permission'
import DetailLink from '@/components/DetailLink'

export default {
  name: 'QuList',
  directives: { permission },
  components: { DetailLink, ImportExcel, RepoSelect, DicListSelect, ChapterSelect, DataTable },
  data() {
    return {

      // 上传头
      header: {},

      // 归属题库ID
      repoId: '',
      repoDetail: {},

      // 章节操作
      chapterDialog: false,
      chapterForm: {
        chapterId: '',
        quIds: ''
      },

      // 难易程度
      levelDialog: false,
      levelForm: {

      },

      // 迁移题库
      repoDialog: false,
      repoForm: {

      },

      importDialog: false,

      listQuery: {
        current: 1,
        size: 10,
        params: {
          content: '',
          quType: '',
          repoId: this.repoId
        }
      },

      options: {

        // 可批量操作
        multi: true,

        add: {
          enable: true,
          permission: 'qu:add'
        },
        edit: {
          enable: true,
          permission: 'qu:update',
          router: { name: 'UpdateQu', params: { id: '$id' }}
        },
        delete: {
          enable: true,
          permission: 'qu:delete',
          url: '/api/qu/qu/delete'
        },

        // 批量操作列表
        multiActions: [
          {
            value: 'join-chapter',
            label: '批量加入章节'
          },
          {
            value: 'clear-chapter',
            label: '清除章节'
          },
          {
            value: 'batch-level',
            label: '设置难易程度'
          },
          {
            value: 'batch-repo',
            label: '批量迁移题库'
          }
        ],
        // 列表请求URL
        listUrl: '/api/qu/qu/paging'
      }
    }
  },

  watch: {
    repoId: {
      handler(val) {
        this.listQuery.params.repoId = val
        this.$refs.pagingTable.getList()
      }
    }
  },

  created() {
    const repoId = this.$route.params.repoId
    if (repoId !== undefined) {
      this.repoId = repoId
      this.listQuery.params.repoId = repoId
    }

    this.header = { token: getToken() }
  },
  methods: {

    handleMultiAction(obj) {
      if (obj.opt === 'join-chapter') {
        this.chapterDialog = true
        this.chapterForm.quIds = obj.ids
      }

      if (obj.opt === 'clear-chapter') {
        this.handlerClearChapters(obj.ids)
      }

      if (obj.opt === 'batch-level') {
        this.levelDialog = true
        this.levelForm.quIds = obj.ids
      }

      if (obj.opt === 'batch-repo') {
        this.repoDialog = true
        this.repoForm.ids = obj.ids
      }
    },

    handlerClearChapters(ids) {
      const postForm = { quIds: ids }

      clearChapters(postForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量清理章节成功！',
          type: 'success',
          duration: 2000
        })

        this.chapterDialog = false
        this.$refs.pagingTable.getList()
      })
    },

    handlerJoinChapters() {
      joinChapters(this.chapterForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量加入章节成功！',
          type: 'success',
          duration: 2000
        })

        this.chapterDialog = false
        this.$refs.pagingTable.getList()
      })
    },

    handlerBatchLevel() {
      batchLevel(this.levelForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量设置难易程度成功！',
          type: 'success',
          duration: 2000
        })

        this.levelDialog = false
        this.$refs.pagingTable.getList()
      })
    },

    handlerBatchRepo() {
      batchRepo(this.repoForm).then(() => {
        this.$notify({
          title: '成功',
          message: '批量迁移题库成功！',
          type: 'success',
          duration: 2000
        })

        this.repoDialog = false
        this.$refs.pagingTable.getList()
      })
    },

    exportExcel() {
      // 导出当前查询的数据
      exportExcel(this.listQuery.params)
    },

    showImport() {
      this.importDialog = true
    },

    importSuccess() {
      this.importDialog = false
      this.$refs.pagingTable.getList()
    },
    handleAdd() {
      this.$router.push({ path: '/admin/repo/qu/add', query: { repoId: this.repoId }})
    },

    // 获取试题内容的显示文本
    getQuestionContent(row) {
      // console.log('Processing row:', row); // 调试用
      
      // 尝试多个可能的字段名
      const possibleFields = ['contentText', 'content', 'questionContent', 'text']
      
      for (const field of possibleFields) {
        if (row[field]) {
          // 如果字段值本身就是一个对象
          if (typeof row[field] === 'object' && row[field].question) {
            return row[field].question
          }
          
          // 如果字段值是字符串，尝试解析JSON
          if (typeof row[field] === 'string') {
            // 如果看起来像JSON（以{开头），尝试解析
            if (row[field].trim().startsWith('{')) {
              try {
                const parsed = JSON.parse(row[field])
                if (typeof parsed === 'object' && parsed.question) {
                  return parsed.question
                }
              } catch (e) {
                // JSON解析失败，可能是截断的JSON，尝试从原始字符串中提取question
                const questionMatch = row[field].match(/"question":"([^"]+)"/)
                if (questionMatch) {
                  return questionMatch[1]
                }
              }
            }
            
            // 如果不是JSON格式，直接返回字符串内容
            if (!row[field].trim().startsWith('{')) {
              return row[field]
            }
          }
        }
      }
      
      // 尝试从任何包含question的字段中提取
      for (const key in row) {
        if (row[key] && typeof row[key] === 'string') {
          const questionMatch = row[key].match(/"question":"([^"]+)"/)
          if (questionMatch) {
            return questionMatch[1]
          }
        }
      }
      
      // 最后返回ID作为兜底
      return row.id || '未知试题'
    },

    // 获取题型显示文本
    getQuestionType(row) {
      // 优先使用字典转换后的文本
      if (row.quType_dictText) {
        return row.quType_dictText
      }
      
      // 如果没有字典文本，尝试从contentText中判断题型
      if (row.contentText) {
        try {
          const parsed = JSON.parse(row.contentText)
          if (typeof parsed === 'object') {
            // 根据JSON结构判断题型
            if (parsed.choose && Array.isArray(parsed.choose)) {
              return '单选题'
            }
            if (parsed.options && Array.isArray(parsed.options)) {
              return '多选题'
            }
            if (parsed.answer === true || parsed.answer === false) {
              return '判断题'
            }
            if (parsed.blanks || (typeof parsed.answer === 'string' && !parsed.choose)) {
              return '填空题'
            }
          }
        } catch (e) {
          // JSON解析失败，忽略
        }
      }
      
      // 使用原始值并进行映射
      if (row.quType) {
        const typeMap = {
          'choice': '单选题',
          'choose': '单选题',
          'multi_choice': '多选题',
          'TF': '判断题',
          'judge': '判断题',
          'fill': '填空题',
          'answer': '简答题',
          'essay': '论述题'
        }
        return typeMap[row.quType] || row.quType
      }
      
      return '单选题' // 默认为单选题
    }
  }
}
</script>
